<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="幅宽" prop="width">
        <el-input v-model="formData.width" placeholder="请输入幅宽" />
      </el-form-item>
      <el-form-item label="修边" prop="trimming">
        <el-input v-model="formData.trimming" placeholder="请输入修边" />
      </el-form-item>
      <el-form-item label="纸板是否有效" prop="isValidPaper">
        <el-radio-group v-model="formData.isValidPaper">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="面纸是否有效" prop="isValidFace">
        <el-radio-group v-model="formData.isValidFace">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="坑纸是否有效" prop="isValidPit">
        <el-radio-group v-model="formData.isValidPit">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="其他是否有效" prop="isValidOther">
        <el-radio-group v-model="formData.isValidOther">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
     <!-- <el-form-item label="适用类型" prop="applyType">
        <el-select v-model="formData.applyType" placeholder="请选择适用类型">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item> -->
	  <el-form-item label="适用类型" prop="applyType">
	    <el-select v-model="formData.applyType" placeholder="请选择材质" clearable @change="handleMaterialChange">
	      <el-option
	        v-for="item in materialList"
	        :key="item.id"
	        :label="item.materialName"
	        :value="item.id"
	      />
	    </el-select>
	  </el-form-item>
      <el-form-item label="毫米幅宽" prop="mmWidth">
        <el-input v-model="formData.mmWidth" placeholder="请输入毫米幅宽" />
      </el-form-item>
      <el-form-item label="英寸幅宽" prop="inchWidth">
        <el-input v-model="formData.inchWidth" placeholder="请输入英寸幅宽" />
      </el-form-item>
      <el-form-item label="计价是否有效" prop="isValidPrice">
        <el-radio-group v-model="formData.isValidPrice">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="方案名称" prop="planName">
        <el-input v-model="formData.planName" placeholder="请输入方案名称" />
      </el-form-item>
      <el-form-item label="修边（双坑）" prop="trimDouble">
        <el-input v-model="formData.trimDouble" placeholder="请输入修边（双坑）" />
      </el-form-item>
      <el-form-item label="修补（三坑）" prop="trimTriple">
        <el-input v-model="formData.trimTriple" placeholder="请输入修补（三坑）" />
      </el-form-item>
      <el-form-item label="适用产品" prop="applyProduct">
        <el-input v-model="formData.applyProduct" placeholder="请输入适用产品" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { BaseOrderPaperConfigApi, BaseOrderPaperConfigVO } from '@/api/erp/baseorderpaperconfig'

/** ERP基础资料-开单参数-原料计算幅宽设置 表单 */
defineOptions({ name: 'BaseOrderPaperConfigForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  width: undefined,
  trimming: undefined,
  isValidPaper: undefined,
  isValidFace: undefined,
  isValidPit: undefined,
  isValidOther: undefined,
  applyType: undefined,
  applyTypeName: undefined,
  mmWidth: undefined,
  inchWidth: undefined,
  isValidPrice: undefined,
  planName: undefined,
  trimDouble: undefined,
  trimTriple: undefined,
  applyProduct: undefined
})
const formRules = reactive({
  // width: [{ required: true, message: '幅宽不能为空', trigger: 'blur' }],
  // trimming: [{ required: true, message: '修边不能为空', trigger: 'blur' }],
  // isValidPaper: [{ required: true, message: '纸板是否有效不能为空', trigger: 'blur' }],
  // isValidFace: [{ required: true, message: '面纸是否有效不能为空', trigger: 'blur' }],
  // isValidPit: [{ required: true, message: '坑纸是否有效不能为空', trigger: 'blur' }],
  // isValidOther: [{ required: true, message: '其他是否有效不能为空', trigger: 'blur' }],
  // applyType: [{ required: true, message: '适用类型不能为空', trigger: 'change' }],
  // mmWidth: [{ required: true, message: '毫米幅宽不能为空', trigger: 'blur' }],
  // inchWidth: [{ required: true, message: '英寸幅宽不能为空', trigger: 'blur' }],
  // isValidPrice: [{ required: true, message: '计价是否有效不能为空', trigger: 'blur' }],
  // planName: [{ required: true, message: '方案名称不能为空', trigger: 'blur' }],
  // trimDouble: [{ required: true, message: '修边（双坑）不能为空', trigger: 'blur' }],
  // trimTriple: [{ required: true, message: '修补（三坑）不能为空', trigger: 'blur' }],
  // applyProduct: [{ required: true, message: '适用产品不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BaseOrderPaperConfigApi.getBaseOrderPaperConfig(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
	  const selectedMaterial = materialList.value.find(item => item.id === formData.value.applyType)
	  formData.value.applyTypeName = selectedMaterial ? selectedMaterial.materialName : ""
    const data = formData.value as unknown as BaseOrderPaperConfigVO
    if (formType.value === 'create') {
      await BaseOrderPaperConfigApi.createBaseOrderPaperConfig(data)
      message.success(t('common.createSuccess'))
    } else {
      await BaseOrderPaperConfigApi.updateBaseOrderPaperConfig(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const materialList = ref<{ id: string; materialName: string }[]>([])

/** 获取材质列表 */
const getAllBaseMaterial = async () => {
  try {
    const response = await BaseOrderPaperConfigApi.getAllBaseMaterial();
    if (response) {
      materialList.value = response;
    }
  } catch (error) {
    console.error("获取材质列表失败:", error);
  }
};

/** 选择材质时，自动填充材质名称 */
const handleMaterialChange = (id: string) => {
  const selectedMaterial = materialList.value.find(item => item.id === id);
  formData.value.applyType = selectedMaterial ? selectedMaterial.id : "";
  formData.value.applyTypeName = selectedMaterial ? selectedMaterial.materialName : "";
};


onMounted(() => {
  Promise.all([
    getAllBaseMaterial()  // 获取所有材质
  ])
})


/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    width: undefined,
    trimming: undefined,
    isValidPaper: undefined,
    isValidFace: undefined,
    isValidPit: undefined,
    isValidOther: undefined,
    applyType: undefined,
    mmWidth: undefined,
    inchWidth: undefined,
    isValidPrice: undefined,
    planName: undefined,
    trimDouble: undefined,
    trimTriple: undefined,
    applyProduct: undefined
  }
  formRef.value?.resetFields()
}
</script>